import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';

class VideoListScreen extends StatefulWidget {
  const VideoListScreen({super.key});

  @override
  State<VideoListScreen> createState() => _VideoListScreenState();
}

class _VideoListScreenState extends State<VideoListScreen> {
  List<File> videoFiles = [];
  bool isLoading = true;
  File? selectedFile;
  VideoPlayerController? _controller;
  bool _isPlaying = false;
  double? _dragMs;
  bool _wasPlayingBeforeDrag = false;

  // 调试功能：创建测试视频文件
  Future<void> _createTestVideo() async {
    try {
      final Directory appDirectory = await getApplicationDocumentsDirectory();
      final String videoDirectory = '${appDirectory.path}/Videos';
      await Directory(videoDirectory).create(recursive: true);
      
      final String testFilePath = '$videoDirectory/test_video.mp4';
      final File testFile = File(testFilePath);
      
      // 创建一个小的测试文件（模拟视频文件）
      await testFile.writeAsString('test video content');
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('测试视频文件已创建')),
      );
      
      _loadVideoFiles(); // 重新加载列表
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('创建测试文件失败: $e')),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    // 延迟加载，确保上下文可用
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadVideoFiles();
    });
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 当页面重新获得焦点时刷新列表
    _loadVideoFiles();
  }

  Future<void> _loadVideoFiles() async {
    try {
      final Directory appDirectory = await getApplicationDocumentsDirectory();
      final String videoDirectory = '${appDirectory.path}/Videos';
      final Directory videoDir = Directory(videoDirectory);

      print('正在检查视频目录: $videoDirectory');
      print('应用文档目录: ${appDirectory.path}');

      if (await videoDir.exists()) {
        print('视频目录存在');
        final List<FileSystemEntity> files = videoDir.listSync();
        print('目录中的文件数量: ${files.length}');
        
        for (var file in files) {
          print('找到文件: ${file.path}');
        }

        final List<File> videos = files
            .where((file) => file.path.endsWith('.mp4'))
            .map((file) => File(file.path))
            .toList()
          ..sort((a, b) => b.lastModifiedSync().compareTo(a.lastModifiedSync()));

        print('MP4视频文件数量: ${videos.length}');

        setState(() {
          videoFiles = videos;
          isLoading = false;
        });
      } else {
        print('视频目录不存在，创建目录...');
        await videoDir.create(recursive: true);
        setState(() {
          videoFiles = [];
          isLoading = false;
        });
      }
    } catch (e) {
      print('加载视频文件时出错: $e');
      setState(() {
        isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载视频文件失败: $e')),
      );
    }
  }

  Future<void> _deleteVideo(File videoFile) async {
    try {
      await videoFile.delete();
      _loadVideoFiles();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('视频已删除')),
      );
    } catch (e) {
      print('Error deleting video: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除视频失败: $e')),
      );
    }
  }

  Future<void> _setSelectedVideo(File videoFile) async {
    if (_controller != null) {
      await _controller!.dispose();
      _controller = null;
      _isPlaying = false;
    }
    selectedFile = videoFile;
    _controller = VideoPlayerController.file(videoFile);
    await _controller!.initialize();
    _controller!.addListener(() {
      if (!mounted) return;
      setState(() {});
    });
    setState(() {});
  }

  void _playPause() {
    if (_controller == null || !_controller!.value.isInitialized) return;
    setState(() {
      if (_controller!.value.isPlaying) {
        _controller!.pause();
        _isPlaying = false;
      } else {
        _controller!.play();
        _isPlaying = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('视频回看'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.bug_report),
            onPressed: _createTestVideo,
            tooltip: '创建测试视频',
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadVideoFiles,
          ),
        ],
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                Container(
                  height: 220,
                  width: double.infinity,
                  color: Colors.black,
                  child: _controller != null && _controller!.value.isInitialized
                      ? Stack(
                          children: [
                            Center(
                              child: AspectRatio(
                                aspectRatio: _controller!.value.aspectRatio,
                                child: VideoPlayer(_controller!),
                              ),
                            ),
                            Positioned(
                              right: 12,
                              bottom: 12,
                              child: FloatingActionButton(
                                mini: true,
                                onPressed: _playPause,
                                child: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
                              ),
                            )
                          ],
                        )
                      : const Center(
                          child: Text(
                            '请选择一个视频进行播放',
                            style: TextStyle(color: Colors.white70),
                          ),
                        ),
                ),
                if (_controller != null && _controller!.value.isInitialized)
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    child: Row(
                      children: [
                        Text(
                          _formatDuration(_controller!.value.position),
                          style: const TextStyle(color: Colors.blueAccent, fontWeight: FontWeight.w600),
                        ),
                        Expanded(
                          child: SliderTheme(
                            data: SliderTheme.of(context).copyWith(
                              showValueIndicator: ShowValueIndicator.onlyForDiscrete,
                            ),
                            child: Slider(
                              min: 0,
                              max: _controller!.value.duration.inMilliseconds == 0
                                  ? 1
                                  : _controller!.value.duration.inMilliseconds.toDouble(),
                              divisions: _buildDivisions(_controller!.value.duration),
                              label: _formatDuration(
                                Duration(
                                  milliseconds: (_dragMs?.round() ?? _controller!.value.position.inMilliseconds),
                                ),
                              ),
                              value: (_dragMs ??
                                      ((_controller!.value.position.inMilliseconds >
                                              _controller!.value.duration.inMilliseconds
                                          ? _controller!.value.duration.inMilliseconds
                                          : _controller!.value.position.inMilliseconds)
                                          .toDouble())),
                              onChangeStart: (v) {
                                _wasPlayingBeforeDrag = _controller!.value.isPlaying;
                                if (_wasPlayingBeforeDrag) {
                                  _controller!.pause();
                                  _isPlaying = false;
                                }
                                setState(() {
                                  _dragMs = v;
                                });
                              },
                              onChanged: (v) {
                                setState(() {
                                  _dragMs = v;
                                });
                              },
                              onChangeEnd: (v) async {
                                await _controller!.seekTo(Duration(milliseconds: v.round()));
                                setState(() {
                                  _dragMs = null;
                                });
                                if (_wasPlayingBeforeDrag) {
                                  _controller!.play();
                                  setState(() {
                                    _isPlaying = true;
                                  });
                                }
                              },
                            ),
                          ),
                        ),
                        Text(
                          _formatDuration(_controller!.value.duration),
                          style: const TextStyle(color: Colors.blueAccent, fontWeight: FontWeight.w600),
                        ),
                      ],
                    ),
                  ),
                if (_controller != null && _controller!.value.isInitialized)
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    child: Row(
                      children: _buildTickLabels(_controller!.value.duration),
                    ),
                  ),
                Expanded(
                  child: videoFiles.isEmpty
                      ? const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.video_library,
                                size: 64,
                                color: Colors.grey,
                              ),
                              SizedBox(height: 16),
                              Text(
                                '暂无录制视频',
                                style: TextStyle(
                                  fontSize: 18,
                                  color: Colors.grey,
                                ),
                              ),
                              SizedBox(height: 8),
                              Text(
                                '点击录制标签开始录制视频',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        )
                      : ListView.builder(
                          itemCount: videoFiles.length,
                          itemBuilder: (context, index) {
                            final videoFile = videoFiles[index];
                            final fileName = videoFile.path.split('/').last;
                            final fileSize = _formatFileSize(videoFile.lengthSync());
                            final modifiedDate = videoFile.lastModifiedSync();
                            final dateString =
                                '${modifiedDate.year}-${modifiedDate.month.toString().padLeft(2, '0')}-${modifiedDate.day.toString().padLeft(2, '0')} '
                                '${modifiedDate.hour.toString().padLeft(2, '0')}:${modifiedDate.minute.toString().padLeft(2, '0')}';

                            return Card(
                              margin: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 8),
                              child: ListTile(
                                leading: Container(
                                  width: 60,
                                  height: 60,
                                  decoration: BoxDecoration(
                                    color: Colors.blue[100],
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: const Icon(
                                    Icons.videocam,
                                    color: Colors.blue,
                                    size: 30,
                                  ),
                                ),
                                title: Text(
                                  fileName,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                subtitle: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('大小: $fileSize'),
                                    Text('时间: $dateString'),
                                  ],
                                ),
                                onTap: () => _setSelectedVideo(videoFile),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.play_arrow),
                                      color: Colors.green,
                                      onPressed: () => _setSelectedVideo(videoFile),
                                    ),
                                    IconButton(
                                      icon: const Icon(Icons.delete),
                                      color: Colors.red,
                                      onPressed: () => _showDeleteDialog(videoFile),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                ),
              ],
            ),
    );
  }

  void _showDeleteDialog(File videoFile) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: const Text('确定要删除这个视频吗？此操作无法撤销。'),
          actions: [
            TextButton(
              child: const Text('取消'),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: const Text('删除'),
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              onPressed: () {
                Navigator.of(context).pop();
                _deleteVideo(videoFile);
              },
            ),
          ],
        );
      },
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '${bytes}B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
  }

  String _formatDuration(Duration d) {
    final hours = d.inHours;
    final minutes = d.inMinutes % 60;
    final seconds = d.inSeconds % 60;
    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    }
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  int? _buildDivisions(Duration d) {
    final totalSec = d.inSeconds;
    if (totalSec <= 0) return null;
    if (totalSec <= 60) return totalSec; // 每秒一个刻度
    if (totalSec <= 600) return totalSec ~/ 5; // 每5秒一个刻度
    return totalSec ~/ 10; // 每10秒一个刻度，避免过密
  }

  List<Widget> _buildTickLabels(Duration d) {
    final totalMs = d.inMilliseconds;
    if (totalMs <= 0) return [];
    final points = [0.0, 0.25, 0.5, 0.75, 1.0];
    return points
        .map((p) => Expanded(
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  _formatDuration(Duration(milliseconds: (totalMs * p).round())),
                  style: const TextStyle(color: Colors.white38, fontSize: 12),
                ),
              ),
            ))
        .toList();
  }
}

class VideoPlayerScreen extends StatefulWidget {
  final File videoFile;

  const VideoPlayerScreen({super.key, required this.videoFile});

  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late VideoPlayerController _controller;
  bool _isPlaying = false;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.file(widget.videoFile)
      ..initialize().then((_) {
        setState(() {});
      });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _playPause() {
    setState(() {
      if (_controller.value.isPlaying) {
        _controller.pause();
        _isPlaying = false;
      } else {
        _controller.play();
        _isPlaying = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('视频播放'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Center(
        child: _controller.value.isInitialized
            ? AspectRatio(
                aspectRatio: _controller.value.aspectRatio,
                child: VideoPlayer(_controller),
              )
            : const CircularProgressIndicator(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _playPause,
        child: Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
      ),
    );
  }
}